package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.service.EsSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class EsSearchController {

    @Autowired
    private EsSearchService esSearchService;


    //比如请求路径是：/search/list?keywords=华为手机&brand=华为
    @GetMapping("/list")
    public String search(@RequestParam Map<String,String> searchMap, Model model){

        //这里特殊处理URL参数有特殊+符号的，回显到页面要显示为2B%
        if(searchMap!=null && searchMap.size()>0){
            for(String key : searchMap.keySet()){
                if(key.startsWith("spec_")){
                    String val = searchMap.get(key);
                    val = val.replace("+",  "%2B");
                    searchMap.put(key, val);
                }
            }
        }


        Map result = esSearchService.search(searchMap);



        //返回所有商品数据
        model.addAttribute("result", result);
        //返回搜索条件
        model.addAttribute("searchMap", searchMap);

        long total = Long.valueOf(String.valueOf(result.get("total")));
        int pageNum = Integer.valueOf(String.valueOf(result.get("pageNum")));
        int pageSize = Page.pageSize;
        Page page = new Page(total, pageNum, pageSize);
        //返回分页数据
        model.addAttribute("page", page);

        StringBuilder url = new StringBuilder();
        url.append("/search/list");
        if(searchMap!=null && searchMap.size()>0){
            url.append("?");
            int flag = 0;
            for(String key : searchMap.keySet()){
                if(!key.equals("sortField") && !key.equals("sortRule") && !key.equals("pageNum")){
                    if(flag>0){
                        url.append("&");
                    }
                    String paramName = key;
                    String paramValue = searchMap.get(key);
                    url.append(paramName+"="+paramValue);
                    flag++;
                }
            }
        }
        //每次请求的完整URL回显到前端
        model.addAttribute("url", url);

        return "search";
    }
}
